package com.loe.mvp.util.dao

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.util.Log
import com.loe.mvp.ext_java.safe
import org.json.JSONArray
import org.json.JSONObject

/**
 * 数据库表类
 */
abstract class DbTable(name: String)
{
    abstract fun onInit(context: Context)

    fun init(context: Context)
    {
        safe()
        {
            DbBase.init(context)
            onInit(context)
        }
    }

    var name: String = name
        private set

    fun go(sql: String?)
    {
        DbBase.db.execSQL(sql)
    }

    /**
     * 删除表
     */
    fun drop()
    {
        DbBase.db.execSQL("drop table $name")
    }

    /**
     * 插入元素
     */
    fun insert(values: ContentValues?): Long
    {
        return DbBase.db.insert(name, null, values)
    }

    /**
     * 替换元素
     */
    fun replace(values: ContentValues?): Long
    {
        return DbBase.db.replace(name, null, values)
    }

    /**
     * 更新元素
     */
    fun update(
        values: ContentValues?,
        whereClause: String?,
        vararg strings: String?
    ): Long
    {
        return DbBase.db.update(name, values, whereClause, strings).toLong()
    }

    /**
     * 删除元素
     */
    fun delete(whereClause: String?, vararg strings: String?): Long
    {
        return DbBase.db.delete(name, whereClause, strings).toLong()
    }

    /**
     * 清除元素
     */
    fun clear()
    {
        DbBase.db.execSQL("delete from $name")
    }

    /**
     * 查询元素
     */
    fun query(): JSONArray
    {
        return query("select * from $name")
    }

    /**
     * 查询元素
     */
    fun query(sql: String?): JSONArray
    {
        val js = JSONArray()
        var cursor: Cursor? = null
        try
        {
            cursor = DbBase.db.rawQuery(sql, null)
            val columnNames = cursor.columnNames
            if (cursor.count != 0)
            {
                while (cursor.moveToNext())
                {
                    val json = JSONObject()
                    for (i in columnNames.indices)
                    {
                        json.put(columnNames[i], cursor.getString(i))
                    }
                    // 添加json到列表
                    js.put(json)
                }
            }
            cursor.close()
        } catch (e: Exception)
        {
            if (cursor != null && !cursor.isClosed)
            {
                cursor.close()
            }
        }
        return js
    }

    /**
     * 查询元素
     */
    fun query(sql: String?, vararg strings: String?): JSONArray
    {
        val js = JSONArray()
        var cursor: Cursor? = null
        try
        {
            cursor = DbBase.db.rawQuery(sql, strings)
            val columnNames = cursor.columnNames
            if (cursor.count != 0)
            {
                while (cursor.moveToNext())
                {
                    val json = JSONObject()
                    for (i in columnNames.indices)
                    {
                        json.put(columnNames[i], cursor.getString(i))
                    }
                    // 添加json到列表
                    js.put(json)
                }
            }
            cursor.close()
        } catch (e: Exception)
        {
            if (cursor != null && !cursor.isClosed)
            {
                cursor.close()
            }
        }
        return js
    }

    /**
     * 开启事物
     */
    fun goTransaction(callBack: () -> Unit): Boolean
    {
        //开启事务
        try
        {
            DbBase.db.beginTransaction()
            callBack()
            //设置事务标志为成功，当结束事务时就会提交事务
            DbBase.db.setTransactionSuccessful()
        } catch (e: Exception)
        {
            Log.e("runtime", e.toString())
            return false
        } finally
        {
            //结束事务
            DbBase.db.endTransaction()
        }
        return true
    }
}